import numpy as np
from typing import Union
from scipy.stats import norm


# (符号) max(0, x) 函数
def I(x: np.ndarray):
    t = np.zeros([x.shape[0], 2])
    t[:, 0] = x
    return np.max(t, axis=1)


# 期望函数
def E(x: Union[np.ndarray, list], p: Union[np.ndarray, list]):
    return np.dot(x, p)


# 依照正态分布计算概率值
def p_norm(x: np.ndarray, mu, sigma):
    init_arr = norm.cdf(x, mu, sigma)
    res_arr = np.zeros(x.shape[0])
    res_arr[0] = init_arr[0]
    # res_arr[0] = init_arr[0] - norm.cdf(x[0] - 1, mu, sigma)
    res_arr[1:] = np.diff(init_arr)
    res_arr[-1] = 1 - init_arr[-2]
    return res_arr


def relative_error(m, n, compare: bool = True):
    if compare:
        _m = np.max([m, n])
        _n = np.min([m, n])
        return (_m - _n) / _n
    else:
        return (n - m) / n

